package com.xzh.rocketmq.service.impl;


import com.mall.common.util.JsonResult;
import com.xzh.mallorderspi.model.Order;
import com.xzh.rocketmq.service.OrderFeignService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * 处理秒杀订单。消费者。
 *
 * @author 臧金玉
 * created on 2025-09-06
 */
@RocketMQMessageListener(topic = "mall-orders", consumerGroup = "g1")
@Service
public class OrderConsumeServiceImpl implements RocketMQListener<Order> {
    private RedisTemplate<String, Object> redisTemplate;
    private OrderFeignService orderFeignService;
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setOrderFeignService(OrderFeignService orderFeignService) {
        this.orderFeignService = orderFeignService;
    }

    @Autowired
    public void setRocketMQTemplate(RocketMQTemplate rocketMQTemplate) {
        this.rocketMQTemplate = rocketMQTemplate;
    }

    //监听到消息队列的消息，即秒杀订单
    @Override
    public void onMessage(Order order) {
        Long ProductId = order.getOrderItems().getFirst().getProductId();

        //创建订单，扣除库存
        try {
            ResponseEntity<JsonResult<?>> re = orderFeignService.save(order);
            JsonResult<?> jr = re.getBody();
            if (jr != null && jr.isSuccess()) {
                Integer orderId = (Integer)jr.getData();//订单主键
                redisTemplate.opsForValue().set("seckill-order:" + order.getSeckillNo(), true, Duration.ofMinutes(30));

                //延迟消息，5分钟后查询订单是否支持
                this.rocketMQTemplate.syncSendDelayTimeSeconds("shoplook2005-orders-check", orderId, 2 * 60);
            }
        } catch (Exception e) {
            //设置此秒杀订单失败
            redisTemplate.opsForValue().set("seckill-order:" + order.getSeckillNo(), false, Duration.ofMinutes(30));
            //redis中秒杀商品数量回滚
            redisTemplate.opsForValue().increment("seckill-stock:" + ProductId, 1);

            throw new RuntimeException(e);
        }
    }
}
